﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Services;
using System.Web.UI;

namespace AgileDashboard.handlers
{
    /// <summary>
    /// Handler that instantiates a named user control along with parameters and returns it's rendered content as an HTML markup fragment
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UCFactory : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            Control ctl = LoadControl(context.Request.QueryString);

            using (var writer = new XhtmlTextWriter(context.Response.Output))
            {
                ctl.RenderControl(writer);
                context.Response.End();
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        private static Control LoadControl(NameValueCollection col)
        {

            UserControl usr = new UserControl();
            var ctl = usr.LoadControl(col["UserControlPath"]);

            // Find the relevant constructor
            if (ctl != null)
            {
                ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(new Type[]{col.GetType()});

                //And then call the relevant constructor
                if (constructor == null)
                {
                    throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType);
                }
                constructor.Invoke(ctl, new object[]{col});
            }

            // Finally return the fully initialized UC
            return ctl;
            
        }

        private static Control LoadControl(string userControlPath, params object[] constructorParameters)
        {
            List<Type> constParamTypes = new List<Type>();
            foreach (object constParam in constructorParameters)
            {
                constParamTypes.Add(constParam.GetType());
            }

            UserControl usr = new UserControl();
            var ctl = usr.LoadControl(userControlPath);

            // Find the relevant constructor
            if (ctl != null)
            {
                ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());

                //And then call the relevant constructor
                if (constructor == null)
                {
                    throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
                }
                constructor.Invoke(ctl, constructorParameters);
            }

            // Finally return the fully initialized UC
            return ctl;
        }
    }
}
